/*
 * LookingGlassCallAst.cpp
 *
 *  Created on: 19 Nov 2010
 *      Author: kn308
 */

#include <MAlice/Parser/location.hh>
#include <sstream>

#include <MAlice/Ast/LookingGlassCallAst.h>
#include <MAlice/Ast/FunctionCallAst.h>
#include <MAlice/Ast/ListAst.h>

namespace MAlice
{

const string LookingGlassCallAst::MANGLING = "Looking-Glass:";

LookingGlassCallAst::LookingGlassCallAst(location loc, const string& name, VariableAst* var) : ExpressionAst(loc),
	mName(name), mVariable(var)
{
	MALICE_TRACE;
}

LookingGlassCallAst::~LookingGlassCallAst()
{
	MALICE_TRACE;
}

llvm::Value* LookingGlassCallAst::generate()
{
	MALICE_TRACE;
	vector<Value*> values;
	values.push_back(mVariable->getPointer());

	if (!values[0])
	{
		stringstream ss;
		ss << "Looking glass '" << mName << "' Passing null pointer. Value* generation failed because of previous errors!" << endl;
		throw runtime_error(ss.str());
	}

	Codegen* g = Codegen::get();
	Builder* builder = g->getBuilder();
	if (Function* F = g->getModule()->getFunction(MANGLING + mName))
	{
		return builder->CreateCall(F, values.begin(), values.end());
	}
	else
	{
		stringstream ss;
		ss << "Looking glass '" << mName << "' is not defined!";
		throw runtime_error(ss.str());
	}

	return NULL;
}

}
